import { NavigateToUrl } from '@/types/uni-pages-type'
import { getToken } from '@/utils/auth'
let timeout = null
const methods = {
  $hrefs(url: NavigateToUrl): void {
    uni.navigateTo({ url })
  },
  $loginUrl(url: NavigateToUrl) {
    if (this.$isLogin()) return
    uni.navigateTo({
      url,
    })
  },
  $isLogin() {
    if (!getToken()) {
      uni.showToast({
        title: '请先登录',
        icon: 'none',
      })
      if (timeout !== null) clearTimeout(timeout)
      timeout = setTimeout(() => {
        uni.navigateTo({
          url: '/pages/index/login',
        })
      }, 1000)
      return true
    }
    return false
  },
  $back(delay = 0) {
    const pages = getCurrentPages()
    setTimeout(() => {
      if (pages.length > 1) {
        uni.navigateBack()
      } else {
        uni.switchTab({
          url: '/pages/index/index',
        })
      }
    }, delay)
  },
  $cdn(url = '', cdnurl = '') {
    if (!url) return ''
    if (url.indexOf('http') === 0) {
      return url
    }
    if (cdnurl === '') {
      cdnurl = import.meta.env.VITE_CDN_URL
    }
    return cdnurl + url
  },
  $static(url = '', staticurl = '') {
    if (staticurl === '') {
      staticurl = import.meta.env.VITE_CDN_URL
    }
    if (staticurl !== 'local') {
      url = this.$cdn(url, staticurl)
    }
    // #ifdef APP-PLUS
    if (staticurl === 'local') {
      url = plus.io.convertLocalFileSystemURL(url)
    }
    // #endif
    // #ifdef H5
    if (staticurl === 'local') {
      url = `/h5${url}`
    }
    // #endif
    return `url(${url})`
  },
  $css(url = '', staticurl = '') {
    if (staticurl === '') {
      staticurl = import.meta.env.VITE_CDN_URL
    }
    if (staticurl !== 'local') {
      url = this.$cdn(url, staticurl)
    }
    // #ifdef APP-PLUS
    if (staticurl === 'local') {
      url = plus.io.convertLocalFileSystemURL(url)
    }
    // #endif
    // #ifdef H5
    if (staticurl === 'local') {
      url = `/h5${url}`
    }
    // #endif
    return `url(${url})`
  },
  $copy(text: string, msg = '复制成功') {
    uni.setClipboardData({
      data: text,
      success: function () {
        uni.showToast({
          title: msg,
        })
      },
    })
  },
  $callPhone(phoneNumber = '') {
    const phone = phoneNumber.toString()
    uni.makePhoneCall({
      phoneNumber: phone,
      fail(err) {
        console.log('makePhoneCall出错', err)
      },
    })
  },
}
uni.$lm = methods
const install = (Vue, options = {}) => {
  // #ifdef VUE3
  for (const key in methods) {
    Vue.config.globalProperties[key] = methods[key]
  }
  // #endif
}
export default install
